package com.qingdai.textmessageservice.listener;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.qingdai.business.entities.CommonResult;
import com.qingdai.textmessageservice.service.TextMessageServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.rmi.ServerException;
import java.util.Arrays;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@RocketMQMessageListener(topic = "QingDai",
        selectorExpression = "textMessageCode",
        consumerGroup = "TEXT_MESSAGE_GROUP",
        instanceName = "instance2"
)
public class SendMessageListener implements RocketMQListener<MessageExt> {
    @Resource
    private TextMessageServiceImpl textMessageService;
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void onMessage(MessageExt message) {
        String phoneNumber = Arrays.toString(message.getBody());
        Random random = new Random();
        Integer code = random.nextInt(1000000);
        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = textMessageService.sentLoginCode(phoneNumber, code);
        } catch (ServerException e) {
            throw new RuntimeException(e);
        }
        if (!Objects.equals(sendSmsResponse.getCode(), "OK")) {

        }
        redisTemplate.opsForValue().set(phoneNumber, code, 30, TimeUnit.SECONDS);  //将验证码存到redis，设置30分钟过期


        //如果消费失败，则抛出RuntimeException，RocketMQ会自动重试
        //可以手动抛出，也可以使用 Lombok 的 @SneakyThrows 注解来抛出 RuntimeException
//        throw new RuntimeException("消费失败");

    }
}


